package de.fzi.kasma.learner.function.kernel;


import java.io.IOException;
import java.util.Set;

import de.fzi.kasma.learner.data.Data;
import de.fzi.kasma.learner.data.Dataset;
import de.fzi.kasma.learner.path.PathEdge;
import de.fzi.kasma.learner.path.PathGraph;
import edu.unika.aifb.graphindex.data.Table;
import edu.unika.aifb.graphindex.query.StructuredQuery;
import edu.unika.aifb.graphindex.searcher.structured.VPEvaluator;
import edu.unika.aifb.graphindex.storage.StorageException;

public class Matrix {
	
	
	public double [][] matrix;
	
	
	public Matrix(Dataset dataset, HypothesisKernel kernel){

		Data[] orderedData = dataset.getAllData();
//		Table <String> result = getQueryResult(dataset, kernel);
		
		matrix = new double [orderedData.length][orderedData.length];
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 1; j < matrix.length; j++) {
					matrix[i][j] = 0;
			}	
		}
        
		for(int i = 0; i<kernel.getClauses().length;i++){
			Table <String> result = null;
			try {
				result = getQueryResult(dataset, kernel.getClauses()[i]);
			} catch (StorageException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			for(int j = 0; j<orderedData.length; j++){
				if(matrix[j][j]==0){
				Data d = orderedData[j];

				if(inResultTable(d,result)){
					matrix[j][j] =1;

				}
				}
			}
			
		}
		        updateMatrix();


	}


	private void updateMatrix() {

		for (int i = 0; i < matrix.length; i++) {
			for (int j = 1; j < matrix.length; j++) {
				if(matrix[i][i]==1 && matrix[j][j] ==1){
					matrix[i][j] = 1;
				}					
			}	
		}
		
	}


	private boolean inResultTable(Data d, Table<String> result) {

        boolean isInResultTable = false;
		for(int i = 0; i<result.rowCount();i++){

			if( (result.getRow(i)[0].equalsIgnoreCase(d.getSourceNode().toString()))&&
				(result.getRow(i)[1].equalsIgnoreCase(d.getTargetNode().toString()))){
				isInResultTable =true;break;
			}
		}return isInResultTable;
	}


	private Table<String> getQueryResult(Dataset dataset, PathGraph pathGraph) throws StorageException {
		
		StructuredQuery q = new StructuredQuery("q1");
		VPEvaluator eval = null;
		try {
			eval = new VPEvaluator(dataset.getIndexReader());
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Set <PathEdge> eset = pathGraph.edgeSet();
		for(PathEdge e : eset){

			q.addEdge(e.getSource().toString(), e.getProperty(),  e.getTarget().toString());

		}
		Table<String> result = null;
		try {
			result = eval.evaluate(q);
		} catch (StorageException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return result;
	}
}
